//
//  NetworkEngine.m
//  Basic
//
//  Created by 裴烨烽 on 16/5/23.
//  Copyright © 2016年 BasicPod. All rights reserved.
//

#import "NetworkEngine.h"
#import "SBJSON.h"
@implementation NetworkEngine

//+ (NetworkEngine *)sharedEngine{
//    static NetworkEngine *_sharedEngine = nil;
//    static dispatch_once_t onceToken;
//    dispatch_once(&onceToken, ^{
//        NSString *baseURLString = @"";
////        if (API_VER.length){
//            if (API_PORT.length){
//                baseURLString = [NSString stringWithFormat:@"http://%@:%@/%@",API_HOST,API_PORT,API_VER];
//            } else {
//
//            }
////        } else {
////            baseURLString = [NSString stringWithFormat:@"http://%@/",API_HOST];
////        }
//        NSURL *baseURL = [NSURL URLWithString:baseURLString];
//    
//        _sharedEngine = [[NetworkEngine alloc] initWithBaseURL:baseURL];
//        _sharedEngine.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
//        _sharedEngine.requestSerializer = [RequestSerializer serializer];
//        _sharedEngine.requestSerializer.timeoutInterval = timeoutInterval;
//        
//        _sharedEngine.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"]; // 设置content-Type为text/html
//        _sharedEngine.responseSerializer = [AFHTTPResponseSerializer serializer];
//    });
//    return _sharedEngine;
//}

-(instancetype)initWithBaseURL:(NSURL *)url {
    self = [super initWithBaseURL:url];
    if (self){
        self.securityPolicy = [AFSecurityPolicy policyWithPinningMode:AFSSLPinningModeNone];
        self.requestSerializer = [RequestSerializer serializer];
        self.requestSerializer.timeoutInterval = timeoutInterval;
        
        self.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"]; // 设置content-Type为text/html
        self.responseSerializer = [AFHTTPResponseSerializer serializer];
    }
    return self;
}




-(void)fetchWithPath:(NSString *)path requestParams:(NSDictionary *)requestParams responseObjectClass:(Class)responseObjectClass succeededBlock:(FetchCompletionHandler)block{
    NSMutableDictionary *tempDic = [NSMutableDictionary dictionaryWithDictionary:requestParams];

    [tempDic setObject:@"ppwhalebaojia" forKey:@"privateKey"];
    [tempDic setObject:[GWTool appName] forKey:@"appType"];
    [tempDic setObject:[GWTool appVersion] forKey:@"appVersion"];
    
    NSString *deviceId = @"";
    if (deviceId.length){
        deviceId = [deviceId substringFromIndex:10];
        [tempDic setObject:deviceId forKey:@"deviceToken"];
    } else {
        NSString *token = [NSString stringWithFormat:@"ppwhalebaojia%li",random() % 1000000000];
        [tempDic setObject:token forKey:@"deviceToken"];
    }
    
    __weak typeof(self)weakSelf = self;
    [self POST:path parameters:tempDic progress:NULL success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (!weakSelf){
            return ;
        }
        if (responseObject == nil){
            NSError *error = [NSError errorWithDomain:ErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey: @"未知错误"}];
            block(NO,nil,error);
        } else {            // 解析成功
            
            dispatch_async(dispatch_get_main_queue(), ^{
                SBJSON *json = [[SBJSON alloc] init];
                NSString *result = [[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
                NSDictionary *dicWithRequestJson = [json objectWithString:result error:nil];
#ifdef DEBUG
                NSLog(@"RESPONSE JSON:%@", dicWithRequestJson );
#endif
                
                // 判断是否成功
                // 1. 判断是否有类别
                if (responseObjectClass == nil){        // 没有返回class
                    block(YES,dicWithRequestJson,nil);
                    return;
                }
                // 2. 判断是否是fetchModel 的子类
                if (![responseObjectClass isSubclassOfClass:[FetchModel class]]) {
                    block(YES,dicWithRequestJson,nil);
                    return;
                }
                // 3. 直接返回
                if ([responseObjectClass instancesRespondToSelector:@selector(initWithJSONDict:)]) {
                    block(YES,dicWithRequestJson,nil);
                }
            });
            NSError *error = [[NSError alloc] initWithDomain:ErrorDomain code:-1 userInfo:@{NSLocalizedDescriptionKey : @"未知错误"}];
            block(NO,nil,error);
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (!weakSelf){
            return ;
        }
        __strong typeof(self)strongSelf = weakSelf;
        
#ifdef DEBUG
        NSString *requestURL = [task.currentRequest.URL absoluteString];
        NSString *params = [[NSString alloc]initWithData:task.currentRequest.HTTPBody encoding:NSUTF8StringEncoding];
        NSLog(@"FAILURE URL:%@ \nPARAMS:%@ \nAND RESPONSE:%@", requestURL, params, task.response);
#endif
        [strongSelf showResponseCode:task.response WithBlock:^(NSInteger statusCode) {
            block(NO,nil,error);
        }];
        
    }];
}



#pragma mark - Other Manger
- (void)showResponseCode:(NSURLResponse *)response WithBlock:(void (^)(NSInteger statusCode))block{
    NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
    NSInteger responseStatusCode = [httpResponse statusCode];
    return block(responseStatusCode);
}


-(NSString *)sortModelManagerWithDic:(NSDictionary *)dict{
    NSString *sortString = @"";
    NSArray *keysArray = [dict allKeys];
    NSArray *resultArray = [keysArray sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        
        return [obj1 compare:obj2 options:NSNumericSearch];
    }];
    for (NSString *categoryId in resultArray) {
        NSString *keyValueString = [dict objectForKey:categoryId];
        
        NSString *key = categoryId;
        NSString *keyValue = keyValueString;
        sortString = [sortString stringByAppendingString:[NSString stringWithFormat:@"%@=%@&",key,keyValue]];
    }
    sortString = [sortString stringByAppendingString:@"pandaolWR@#!DFS"];
    return sortString;
    
}


@end
